Mastering Python: a Comprehensive Guide by Américo Moreira
Author:Américo Moreira
Language: eng
Format: epub
Publisher: Ocirema
Published: 2023-09-29T00:00:00+00:00
Chapter 7 - File Handling and Input/Output
7.1 Reading and Writing Files
In Python, file handling is an essential skill that allows you to work with different types of files, such as text files, CSV files, JSON files, and more. In this section, we will explore how to read and write files using Python.
Opening and Closing Files
Before we can read or write to a file, we need to open it. Python provides a built-in function called open() that allows us to open a file in different modes, such as read mode ('r'), write mode ('w'), append mode ('a'), and more. Hereâs the basic syntax for opening a file:
file = open('filename', 'mode')
In the above syntax, 'filename' represents the name of the file you want to open, and 'mode' represents the mode in which you want to open the file.
Once we are done working with a file, it is important to close it to free up system resources. We can use the close() method to close the file. Hereâs an example:
file = open('filename', 'mode')
# Perform file operations
file.close()
Reading Files
To read the contents of a file, we can use the read() method. This method reads the entire contents of the file as a string. Hereâs an example:
file = open('filename', 'r')
content = file.read()
print(content)
file.close()
In the above example, we open the file in read mode ('r'), read its contents using the read() method, and then print the content. Finally, we close the file using the close() method.
If you want to read only a certain number of characters from a file, you can pass the number of characters as an argument to the read() method. For example, to read the first 100 characters of a file, you can use the following code:
file = open('filename', 'r')
content = file.read(100)
print(content)
file.close()
Writing Files
To write to a file, we need to open it in write mode ('w'). If the file does not exist, Python will create it. If the file already exists, opening it in write mode will overwrite its contents. Hereâs an example:
file = open('filename', 'w')
file.write('Hello, World!')
file.close()
In the above example, we open the file in write mode ('w'), write the string 'Hello, World!' to the file using the write() method, and then close the file.
If you want to append content to an existing file instead of overwriting it, you can open the file in append mode ('a'). Hereâs an example:
file = open('filename', 'a')
file.write('This is additional content.')
file.close()
In the above example, we open the file in append mode ('a'), write the string 'This is additional content.' to the file, and then close the file.
Error Handling
When working with files, it is important to handle potential errors that may occur. One common error is when the file you are trying to open does not exist. To handle such errors, you can use a try-except block. Hereâs an example:
try:
file = open('filename', 'r')
content = file.read()
print(content)
file.close()
except FileNotFoundError:
print('File not found.')
In the above example, we try to open the file and read its contents. If the file does not exist, a FileNotFoundError will be raised, and the code inside the except block will be executed.
Download
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Hello! Python by Anthony Briggs(9399)
OCA Java SE 8 Programmer I Certification Guide by Mala Gupta(9364)
The Mikado Method by Ola Ellnestam Daniel Brolund(9330)
Algorithms of the Intelligent Web by Haralambos Marmanis;Dmitry Babenko(7873)
Sass and Compass in Action by Wynn Netherland Nathan Weizenbaum Chris Eppstein Brandon Mathis(7419)
Test-Driven iOS Development with Swift 4 by Dominik Hauser(7369)
Grails in Action by Glen Smith Peter Ledbrook(7313)
The Well-Grounded Java Developer by Benjamin J. Evans Martijn Verburg(7140)
Secrets of the JavaScript Ninja by John Resig Bear Bibeault(5979)
Kotlin in Action by Dmitry Jemerov(4662)
Hands-On Full-Stack Web Development with GraphQL and React by Sebastian Grebe(3941)
Functional Programming in JavaScript by Mantyla Dan(3730)
Learning Java by Patrick Niemeyer & Daniel Leuck(2878)
Windows APT Warfare by Sheng-Hao Ma(2875)
Mastering Python for Finance by Weiming James Ma;(2858)
Learning React: Functional Web Development with React and Redux by Banks Alex & Porcello Eve(2850)
WordPress Plugin Development Cookbook by Yannick Lefebvre(2635)
Mastering Java 9 by Dr. Edward Lavieri(2578)
Architecting Modern Java EE Applications: Designing lightweight, business-oriented enterprise applications in the age of cloud, containers, and Java EE 8 by Daschner Sebastian(2566)